package cn.com.cpic.insurance.rulecheck.web;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import cn.com.cpic.insurance.rulecheck.entity.Rule;
import cn.com.cpic.insurance.rulecheck.entity.RuleDefinition;
import cn.com.cpic.insurance.rulecheck.service.RuleDefinitionService;
import cn.com.cpic.insurance.rulecheck.service.RuleService;

@Results({ @Result(name = CrudActionSupport.RELOAD, location = "rule.action", type = "redirect", params = {
		"conditionId", "${conditionId}" }) })
public class RuleAction extends CrudActionSupport<Rule> {

	private static final long serialVersionUID = -5086505209066238266L;

	private RuleService service;

	private RuleDefinitionService rdService;

	private Long id;

	private Long conditionId;

	private Rule entity;

	private List<Rule> items;

	private List<RuleDefinition> definitions;

	@Override
	public String execute() {
		return list();
	}

	public String list() {
		if (conditionId != null) {
			items = service.getRuleList(conditionId);
		}
		return SUCCESS;
	}

	public String input() {
		prepareModel();
		definitions = rdService.getRuleDefinitionList();
		return INPUT;
	}

	public String save() {
		// 两种情况需要复制规则定义：
		// 1. 匹配条件之前未指定过规则定义
		// 2. 匹配条件之前指定了规则定义并且修改了指定的规则定义
		boolean copyRuleItemFromDef = false;
		if (entity.getId() == null) {
			copyRuleItemFromDef = true;
		} else {
			Rule rule = service.getRule(entity.getId());
			copyRuleItemFromDef = entity.getRuleDefinitionId() != rule.getRuleDefinitionId();
			service.saveRule(entity);
		}
		long id = service.saveRule(entity);
		if (copyRuleItemFromDef) {
			service.copyRuleItemsFromDef(id, entity.getRuleDefinitionId());
		}
		return RELOAD;
	}

	public String delete() {
		service.deleteRule(this.id);
		return RELOAD;
	}

	protected void prepareModel() {
		if (id != null) {
			this.entity = service.getRule(id);
		} else {
			this.entity = new Rule();
			this.entity.setConditionId(this.conditionId);
		}
	}

	@Autowired
	public void setService(RuleService service) {
		this.service = service;
	}

	@Autowired
	public void setRdService(RuleDefinitionService rdService) {
		this.rdService = rdService;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long getConditionId() {
		return conditionId;
	}

	public void setConditionId(String id) {
		if (StringUtils.isNotBlank(id)) {
			this.conditionId = Long.parseLong(id);
		}
	}

	public List<Rule> getItems() {
		return items;
	}

	public List<RuleDefinition> getDefinitions() {
		return definitions;
	}

	public Rule getModel() {
		return entity;
	}
}
